
/**
 * Copyright 2009 cestum.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package org.waveprotocol.wave.model.document.operation.algorithm.transformer {
import org.waveprotocol.wave.model.document.operation.AnnotationBoundaryMap;
import org.waveprotocol.wave.model.document.operation.Attributes;
import org.waveprotocol.wave.model.document.operation.AttributesUpdate;
import org.waveprotocol.wave.model.document.operation.BufferedDocOp;
import org.waveprotocol.wave.model.document.operation.EvaluatingDocOpCursor;
/**
 * A target of a document mutation which can be used to transform document
 * mutations by making use primarily of information from one mutation with the
 * help of auxiliary information from a second mutation. These targets should
 * be used in pairs.
 */
final class Target implements EvaluatingDocOpCursor {
	
	var parent:Transformer;
	
	private var retainCache:RangeCache;
	/**
	 * The target to which to write the transformed mutation.
	 */
	var targetDocument:EvaluatingDocOpCursor;
	private var relativePosition:RelativePosition;
	
	/**
	 * An annotation tracker that tracks annotation modifications at the current
	 * cursor position.
	 */
	private var annotationTracker:AnnotationTracker;
	var otherTarget:Target;
	var rangeCache:RangeCache= retainCache;
	var depth:int= 0;
	
	function Target(t:Transformer, targetDocument:EvaluatingDocOpCursor, relativePosition:RelativePosition,
					annotationTracker:AnnotationTracker) {
		this.targetDocument = targetDocument;
		this.relativePosition = relativePosition;
		this.annotationTracker = annotationTracker;
		this.parent = t;
		retainCache = new RetainRangeCache(this);
	}
	
	public function setOtherTarget(otherTarget:Target):void {
		this.otherTarget = otherTarget;
	}
	
	public function finish():BufferedDocOp {
		annotationTracker.flush();
		return BufferedDocOp(targetDocument.finish());
	}
	
	
	public function retain(itemCount:int):void {
		resolveRange(itemCount, Transformer.retainResolver);
		rangeCache = retainCache;
	}
	
	
	public function characters(chars:String):void {
		if (otherTarget.depth > 0) {
			otherTarget.annotationTracker.startDeletion();
			otherTarget.targetDocument.deleteCharacters(chars);
			otherTarget.annotationTracker.endDeletion();
		} else {
			prepareForInsertion();
			targetDocument.characters(chars);
			otherTarget.targetDocument.retain(chars.length);
		}
	}
	
	
	public function elementStart(tag:String, attrs:Attributes):void {
		if (otherTarget.depth > 0) {
			otherTarget.annotationTracker.startDeletion();
			otherTarget.targetDocument.deleteElementStart(tag, attrs);
			otherTarget.annotationTracker.endDeletion();
		} else {
			prepareForInsertion();
			targetDocument.elementStart(tag, attrs);
			otherTarget.targetDocument.retain(1);
		}
	}
	
	
	public function elementEnd():void {
		if (otherTarget.depth > 0) {
			otherTarget.annotationTracker.startDeletion();
			otherTarget.targetDocument.deleteElementEnd();
			otherTarget.annotationTracker.endDeletion();
		} else {
			prepareForInsertion();
			targetDocument.elementEnd();
			otherTarget.targetDocument.retain(1);
		}
	}
	
	
	public function deleteCharacters(chars:String):void {
		var resolutionSize:int= resolveRange(chars.length, new DeleteCharactersResolver(chars));
		if (resolutionSize >= 0) {
			rangeCache = new DeleteCharactersCache(this, chars.substring(resolutionSize));
		}
	}
	
	
	public function deleteElementStart(tag:String, attrs:Attributes):void {
		if (resolveRange(1, new DeleteElementStartResolver(tag, attrs)) == 0) {
			rangeCache = new DeleteElementStartCache(this,tag, attrs);
		}
	}
	
	
	public function deleteElementEnd():void {
		if (resolveRange(1, Transformer.deleteElementEndResolver) == 0) {
			rangeCache = new DeleteElementEndCache(this);
		}
	}
	
	
	public function replaceAttributes(oldAttrs:Attributes, newAttrs:Attributes):void {
		if (resolveRange(1, new ReplaceAttributesResolver(oldAttrs, newAttrs)) == 0) {
			rangeCache = new ReplaceAttributesCache(this, oldAttrs, newAttrs);
		}
	}
	
	
	public function updateAttributes(attrUpdate:AttributesUpdate):void {
		if (resolveRange(1, new UpdateAttributesResolver(attrUpdate)) == 0) {
			rangeCache = new UpdateAttributesCache(this, attrUpdate);
		}
	}
	
	
	public function annotationBoundary(map:AnnotationBoundaryMap):void {
		annotationTracker.buffer(map);
	}
	
	/**
	 * Resolves the transformation of a range.
	 */
	function resolveRange(size:int, resolver:RangeResolver):int {
		var oldPosition:int= relativePosition.getPos();
		relativePosition.increase(size);
		if (relativePosition.getPos() > 0) {
			if (oldPosition < 0) {
				resolver.resolve(-oldPosition, otherTarget.rangeCache);
			}
			return -oldPosition;
		} else {
			resolver.resolve(size, otherTarget.rangeCache);
			return -1;
		}
	}
	
	function flushAnnotations():void {
		annotationTracker.flush();
		otherTarget.annotationTracker.flush();
		annotationTracker.sync();
		otherTarget.annotationTracker.sync();
	}
	
	function doDeleteCharacters(chars:String):void {
		annotationTracker.flush();
		annotationTracker.sync();
		annotationTracker.startDeletion();
		targetDocument.deleteCharacters(chars);
		annotationTracker.endDeletion();
	}
	
	function doDeleteElementStart(type:String, attrs:Attributes):void {
		annotationTracker.flush();
		annotationTracker.sync();
		annotationTracker.startDeletion();
		targetDocument.deleteElementStart(type, attrs);
		annotationTracker.endDeletion();
	}
	
	function doDeleteElementEnd():void {
		annotationTracker.flush();
		annotationTracker.sync();
		annotationTracker.startDeletion();
		targetDocument.deleteElementEnd();
		annotationTracker.endDeletion();
	}
	
	function prepareForInsertion():void {
		annotationTracker.flush();
		annotationTracker.sync();
		otherTarget.annotationTracker.sync();
	}
	
	function dualDeletion():void {
		annotationTracker.processAll();
		otherTarget.annotationTracker.processAll();
	}
	
}
}